package org.bozo.im.activity.roster;

import java.util.ArrayList;

import org.bozo.im.R;
import org.bozo.im.common.types.Protocol;
import org.bozo.im.common.types.RawContact;
import org.bozo.im.common.utils.PresenceUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class RawAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private Context mContext;
	private ArrayList<RawContact> mContacts;
	private OnClickListener mListener;

	public RawAdapter(Context pContext, ContactAggregator pContact, OnClickListener pListener) {
		mContext = pContext;
		mContacts = pContact.getContacts();
		mListener = pListener;
	}

	public int getCount() {
		return mContacts.size();
	}

	public Object getItem(int pPosition) {
		return mContacts.get(pPosition);
	}

	public long getItemId(int pPosition) {
		return mContacts.hashCode();
	}

	public View getView(int pPosition, View pConvertView, ViewGroup pParent) {

		View lView = pConvertView;
		RawContactHolder lHolder;

		if (mInflater == null)
			mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		if (lView == null) {

			lView = mInflater.inflate(R.layout.rawcontact_item, null);
			lView.setClickable(true);
			lView.setOnClickListener(mListener);

			lHolder = new RawContactHolder();

			lHolder.protocolText = (TextView)lView.findViewById(R.id.rawcontact_protocol);
			lHolder.id = (TextView)lView.findViewById(R.id.rawcontact_id);
			lHolder.presence = (ImageView)lView.findViewById(R.id.rawcontact_presence);

			lView.setTag(lHolder);
		} else {
			lHolder = (RawContactHolder)lView.getTag();
		}

		RawContact lContact = (RawContact)getItem(pPosition);

		if (lContact != null) {
			lHolder.handle = lContact.getId();
			lHolder.protocol = lContact.getProtocol();
			lHolder.protocolText.setText(mContext.getResources().getString(lContact.getProtocol().getRessourceId()));
			lHolder.id.setText(lContact.getId());
			lHolder.presence.setImageResource(PresenceUtils.toImageId(lContact.getPresence()));
		}

		return lView;
	}

	public static class RawContactHolder {
		TextView protocolText;
		TextView id;
		ImageView presence;
		String handle;
		Protocol protocol;
	}
}
